//
//  CXRecommendViewController.m
//  Travel
//
//  Created by dllo on 15/11/28.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "CXRecommendViewController.h"
#import "CXNetHandle.h"
#import "UIImageView+WebCache.h"
#import "KHHRecommendModel.h"
#import "KHHLunboNextViewController.h"
#import "KHHheaderScrollView.h"
#import "KHHStoryAllPageViewController.h"
#import "KHHStoryDetailPageViewController.h"
#import "KHHStoryItemCollectionViewCell.h"
#import "KHHStoryCollectionViewCell.h"
#import "KHHRecommendIndexViewCell.h"
#import "MJRefresh.h"
#import "KHHTravelNotesDetailPageViewController.h"
#import "KHHSearchViewController.h"
#import "KHHSearchCollectionViewController.h"
#import "FujinViewController.h"

@interface CXRecommendViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, UISearchBarDelegate, jumpToWebView>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr; //推荐首页总数组
@property (nonatomic, strong) NSMutableArray *ScrollViewDataArr;//轮播图数据
@property (nonatomic, strong) UIImageView *image;//最后一张轮播图片
@property (nonatomic, strong) NSTimer *timer; //定时器
@property (nonatomic, strong) NSMutableArray *storyArr;
@property (nonatomic, strong) NSMutableArray *modelStoryDataArr; //转化为model的story数组
@property (nonatomic, strong) NSMutableArray *modelUserDataArr; // 转化为model的story中的user数组
@property (nonatomic, strong) NSMutableArray *modelTravelDataArr;
@property (nonatomic, strong) NSMutableArray *modelTravelUserArr;
@property (nonatomic, strong) NSMutableArray *modelDetailStoryArr;//转化为对象的故事详情数组
@property (nonatomic, strong) UIView *viewTitle1; //第一个分区头view
@property (nonatomic, strong) NSNumber *next_start; //下一页数据

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *modelSearchArr;
@property (nonatomic, strong) NSMutableArray *modelSearchElementsArr;
@property (nonatomic, strong) UIView *nightView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) KHHheaderScrollView *headerScrollView;  //轮播图
@end

@implementation CXRecommendViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //当控制器上存在滑动视图时 给滑动视图添加上边距(0 , 64)
    self.navigationController.navigationBar.translucent = NO;
    //导航颜色
    //self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.35 green:0.73 blue:0.78 alpha:1];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(fujin)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    //获取数据
    [self getData];
    //创建tableView
    [self createMainTableView];
    [self SearchBar];

    //菊花
    [CXLoadMBProgress loadMBProgress:self.view];

}

//fujing
- (void)fujin
{
    FujinViewController *fujinVC = [[FujinViewController alloc] init];
    
    [self.navigationController pushViewController:fujinVC animated:YES];
}

//即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController.navigationBar viewWithTag:20000].hidden = YES;
}

//即将出现
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController.navigationBar viewWithTag:20000].hidden = NO;
}

- (void)JudgeNet
{
    //网络状态
    [CXRecommendViewController networkReachabilityStatus:^(id result) {
        if ([result isEqualToNumber:@0]) {
            UIAlertController *altController = [UIAlertController alertControllerWithTitle:@"亲 " message:[NSString stringWithFormat:@"%@", @"您的网络状态不佳哦"] preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:altController animated:YES completion:^{
                
            }];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"你还能咋地?");
                [altController dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }];
            [altController addAction:cancle];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"想咋地就咋地");
                
            }];
            [altController addAction:sure];
        }
    }];
}

#pragma mark - 获取推荐首页数据
- (void)getData
{
    
    NSString *url = @"http://api.breadtrip.com/v2/index/?lat=38.8802706535603&lng=121.54089204778&sign=dfcaa3638dd2a27e24a726ba2d2fd3cd";
    
    [CXNetHandle getUrl:url cookie:nil result:^(id result) {
        
        if (result == nil) {
            return ;
        }
        
        //移除菊花
        [CXLoadMBProgress removeMBProgress:self.view];
    
        //接收总字典
        NSMutableDictionary *tempDic = result;
        
        if (tempDic.count == 0) {
            [self JudgeNet];
            return ;
        }
        
        //下一页id
        self.next_start = tempDic[@"data"][@"next_start"];
        
        //首页总数据
        self.dataArr = tempDic[@"data"][@"elements"];
        self.ScrollViewDataArr = [NSMutableArray array];
        //轮播图数组
        for (NSMutableDictionary  *dic in [self.dataArr[0] objectForKey:@"data"][0]) {
            
            [self.ScrollViewDataArr addObject:dic];
        }
        
        if (self.ScrollViewDataArr.count != 0) {
            // 创建轮播图
            [self createHeaderScrollView];
        }
        
        
        //搜索页数据
        self.modelSearchArr = [KHHRecommendModel transformWithArray:tempDic[@"data"][@"search_data"]];
        self.modelSearchElementsArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in tempDic[@"data"][@"search_data"] ) {
            [self.modelSearchElementsArr addObject: [KHHRecommendModel transformWithArray:dic[@"elements"]]];
            
        }
        
#if 1   /*story数据   */
        //创建一个数组 用来存放所有type == 10的字典
        NSMutableArray *typeArr = [NSMutableArray array];
        for (NSDictionary *dic in self.dataArr) {
            
            NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
            if ([type isEqualToString:@"10"]) {
                [typeArr addObject:dic];
            }
        }
        
        //创建一个数组 用来接收四个view的数据
        NSMutableArray *typeDataArr = [NSMutableArray array];
        for (NSDictionary *dic in typeArr) {
            [typeDataArr addObject: dic[@"data"][0]];
        }
        
        //创建一个数组 用来接收四个view中user信息的数据
        NSMutableArray *typeUserArr = [NSMutableArray array];
        for (NSDictionary *dic in typeDataArr) {
            [ typeUserArr addObject: dic[@"user"]];
        }
        
        self.modelStoryDataArr = [KHHRecommendModel transformWithArray:typeDataArr];
        self.modelUserDataArr = [KHHRecommendModel transformWithArray:typeUserArr];
#endif
        
#if 1   /* 游记数据  */
        //创建一个数组 用来存放所有type == 4的字典
        NSMutableArray *travelArr = [NSMutableArray array];
        for (NSDictionary *dic in self.dataArr) {
            
            NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
            if ([type isEqualToString:@"4"]) {
                [travelArr addObject:dic];
                // NSLog(@"%@",  dic[@"data"][0] [@"name"]);
            }
        }
        //创建一个数组 用来接收view的数据
        NSMutableArray *travelDataArr = [NSMutableArray array];
        for (NSDictionary *dic in travelArr) {
            [travelDataArr addObject: dic[@"data"][0]];
        }
        //创建一个数组 用来接收四个view中user信息的数据
        NSMutableArray *travelUserArr = [NSMutableArray array];
        for (NSDictionary *dic in travelDataArr) {
            [travelUserArr addObject: dic[@"user"]];
        }
        self.modelTravelDataArr = [KHHRecommendModel transformWithArray:travelDataArr];
        self.modelTravelUserArr = [KHHRecommendModel transformWithArray:travelUserArr];
        
#endif
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }];
    
}

#pragma mark - 创建searchBar
- (void)SearchBar
{
    UIButton *titLeView = [[UIButton alloc] initWithFrame:CGRectMake(20, 5, WIDTH - 80 , 30)];
    titLeView.tag = 20000;
    [titLeView addTarget:self action:@selector(pushToSearch) forControlEvents:UIControlEventTouchUpInside];
    //titLeView.backgroundColor = [UIColor redColor];
    [self.navigationController.navigationBar addSubview:titLeView];

    
    // 初始化
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, WIDTH - 80, 30)];
    // 设置代理
    self.searchBar.delegate = self;
    //类型
    [self.searchBar setBarStyle:UIBarStyleDefault];
    //提示文本
    self.searchBar.placeholder = @"搜索目的地  游记...";
    
    //键盘类型
    [self.searchBar setKeyboardType:UIKeyboardTypeDefault];
    
    //视图剪切
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.cornerRadius = 6;
    
    //关闭用户交互
    self.searchBar.userInteractionEnabled = NO;
    [titLeView addSubview:self.searchBar];
    
    
}

#pragma mark - 搜索按钮触发方法
- (void)pushToSearch
{
    
    KHHSearchCollectionViewController *search = [[KHHSearchCollectionViewController alloc]init];
    search.hidesBottomBarWhenPushed = YES;
    search.modelSearchArr = self.modelSearchArr;
    search.modelSearchElementsArr = self.modelSearchElementsArr;
    [self.navigationController pushViewController:search animated:YES];
    
    [self.view viewWithTag:20000].hidden = YES;
    
}


#pragma mark - MJ刷新
- (void)MJRefresh
{
    //MJ下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self getData];
    }];
    [self.tableView.mj_header endRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *url = [ NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?next_start=%@", self.next_start];
        [CXNetHandle getUrl:url cookie:nil result:^(id result) {
            
            NSMutableDictionary *dic = result;
            //接收总字典
            NSMutableDictionary *tempDic = result;
            
            //下一页id
            self.next_start = tempDic[@"data"][@"next_start"];
            
            
            NSMutableArray *tempArr =  dic[@"data"][@"elements"];
            
            //创建一个数组 用来存放所有type == 4的字典
            NSMutableArray *travelArr = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                
                NSString *type = [NSString stringWithFormat:@"%@", dic[@"type"]];
                if ([type isEqualToString:@"4"]) {
                    [travelArr addObject:dic];
                }
            }
            
            
            //创建一个数组 用来接收view的数据
            NSMutableArray *travelDataArr = [NSMutableArray array];
            for (NSDictionary *dic in travelArr) {
                [ travelDataArr addObject: dic[@"data"][0]];
            }
            
            
            //把之后页面的对象数组中的对象 加到原对象数组中
            [self.modelTravelDataArr addObjectsFromArray:[KHHRecommendModel transformWithArray:travelDataArr]];
            
            //user数据加到原对象数组中
            NSMutableArray *userDataArr = [NSMutableArray array];
            for (NSDictionary *dic in tempArr) {
                NSMutableDictionary *tempDic = dic[@"data"][0][@"user"];
                [userDataArr addObject:tempDic];
            }
            [self.modelTravelUserArr addObjectsFromArray:[KHHRecommendModel transformWithArray:userDataArr]];
        
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        }];
        
        
    }];
}

#pragma mark - 创建tableView
- (void)createMainTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    [self.view addSubview:self.tableView];
    
    //注册cell
    [self.tableView registerClass:[KHHStoryCollectionViewCell class] forCellReuseIdentifier:@"story"];
    [self.tableView registerClass:[KHHRecommendIndexViewCell class] forCellReuseIdentifier:@"travel"];
    
    //明杰刷新
    [self MJRefresh];
}

#pragma mark - 创建轮播图
- (void)createHeaderScrollView
{
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HEIGHT, 200)];
    self.tableView.tableHeaderView = self.headerView;
    self.headerScrollView = [[KHHheaderScrollView alloc]initWithFrame:self.headerView.frame dataArr:self.ScrollViewDataArr];
    
    //设置代理人
    self.headerScrollView.delegate = self;

    [self.headerView addSubview:self.headerScrollView];
}

#pragma mark - 轮播图实现协议方法
- (void)jumptoWebView:(NSString *)str
{
    KHHLunboNextViewController *webView = [[KHHLunboNextViewController alloc]init];
    webView.urlStr = str;
    webView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
}


#pragma mark - 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


#pragma mark - 分区头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 54;
        
    } else {
        
        return 34;
    }
}

#pragma mark - 分区头view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
#pragma mark - 第一个section的分区头view
    self.viewTitle1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    
    UILabel *blueLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 20 , 5, 24)];
    blueLable.backgroundColor = [UIColor colorWithRed:0.35 green:0.73 blue:0.78 alpha:1];
    [self.viewTitle1 addSubview:blueLable];
    blueLable.layer.masksToBounds = YES;
    blueLable.layer.cornerRadius = 2;
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(25, blueLable.frame.origin.y, WIDTH - 25 , blueLable.frame.size.height)];
    titleLable.textColor = [UIColor darkGrayColor];
    titleLable.font = [UIFont fontWithName:@"Arial-Bold" size:15];
    titleLable.text = self.dataArr[1][@"data"][0][@"title"];
    [self.viewTitle1 addSubview:titleLable];
    
    //全部按钮
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(WIDTH - 90, blueLable.frame.origin.y, 90, blueLable.frame.size.height);
    
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setTitle:@"全部" forState:UIControlStateNormal];
    [self.viewTitle1 addSubview:btn];
    [btn addTarget:self action:@selector(allPageAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imgAllRight = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"allRight"]];
    imgAllRight.frame = CGRectMake(65, 3, 20, btn.frame.size.height - 5);
    
    [btn addSubview:imgAllRight];
    
    
    
    
    
#pragma mark - 第二个section的分区头view
    UIView *viewTitle2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    
    
    UILabel *blueLable1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 0 , 5, 24)];
    blueLable1.backgroundColor = [UIColor colorWithRed:0.35 green:0.73 blue:0.78 alpha:1];
    [viewTitle2 addSubview:blueLable1];
    
    blueLable1.layer.masksToBounds = YES;
    blueLable1.layer.cornerRadius = 2;
    
    UILabel *titleLable1 = [[UILabel alloc] initWithFrame:CGRectMake(25, blueLable1.frame.origin.y, WIDTH - 25 , blueLable.frame.size.height)];
    titleLable1.textColor = [UIColor darkGrayColor];
    titleLable1.font = [UIFont fontWithName:@"Arial-Bold" size:15];
    titleLable1.text =  self.dataArr[6][@"data"][0][@"title"];
    
    [viewTitle2 addSubview:titleLable1];
    
    
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"])
//    {
//        titleLable.textColor  = [UIColor whiteColor];
//        titleLable1.textColor = [UIColor whiteColor];
//        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        
//    }
    
    if (section == 0) {
        
        return self.viewTitle1;
        
    } else {
        
        return viewTitle2;
    }
}


#pragma mark - 故事分区 全部按钮触发事件
- (void)allPageAction
{
    KHHStoryAllPageViewController *story = [[KHHStoryAllPageViewController alloc]init];
    story.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:story animated:YES];
}

#pragma mark - tableView  分行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
        
    } else {
        return self.modelTravelDataArr.count;
    }
    
}

#pragma mark - tableView 数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //每日精选故事数据
    if (indexPath.section == 0) {
        KHHStoryCollectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"story"];
        
        cell.delegate = self;
        cell.dataSource = self;
        [cell.collectionView reloadData];
        return cell;
        
    } else {
        //游记数据
        
        KHHRecommendIndexViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travel"];
        cell.travelModel = self.modelTravelDataArr[indexPath.row];
        cell.travelUserModel = self.modelTravelUserArr[indexPath.row] ;
        
        return cell;

   }

}


#pragma mark - tableView Cell 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //游记分区
    if (indexPath.section == 1) {
        KHHTravelNotesDetailPageViewController *travelNotes = [[KHHTravelNotesDetailPageViewController alloc] init];
        travelNotes.travelNotesModel = self.modelTravelDataArr[indexPath.row];
        travelNotes.hidesBottomBarWhenPushed = YES;
        
        //收藏时 把前一页的对象传递过去  用来获取图片文字
        travelNotes.recommendModel = self.modelTravelDataArr[indexPath.row];
        travelNotes.recommentUserModel = self.modelTravelUserArr[indexPath.row];
        
        travelNotes.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:travelNotes animated:YES];
    
    }
    
}

#pragma mark - tableView行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 510;
        
    } else {
        
        KHHRecommendModel *tempModel = self.modelTravelDataArr[indexPath.row];
        //自适应标题
        CGFloat HTitleLable = [[self class]heightWithText:tempModel.name fontSize:18 Width:WIDTH - 40];
        return    5 + 10 + HTitleLable + 10 + 15 + 5 + 15 + 200 / 4 + 10 + 10 + (WIDTH - 20) / 6;
    }
}

#pragma mark - 协议方法 item个数

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KHHStoryItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StoryItemitem" forIndexPath:indexPath];
    
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"])
//    {
//       cell.backgroundColor = [UIColor blackColor];
//    } else {
//        cell.backgroundColor = [UIColor whiteColor];
//    }
    
    cell.recommendModel = self.modelStoryDataArr[indexPath.item];
    cell.userModel = self.modelUserDataArr[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    KHHStoryDetailPageViewController *storyDetail = [[KHHStoryDetailPageViewController alloc] init];
    storyDetail.spot_id = ((KHHRecommendModel *)self.modelStoryDataArr[indexPath.item]).spot_id;
    
//    //收藏时拿到前页数据
    storyDetail.recommendModel = self.modelStoryDataArr[indexPath.item];
    storyDetail.userModel = self.modelUserDataArr[indexPath.item];
    
    storyDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:storyDetail animated:YES];
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
